package com.gxa.jjty.admin.controller;

import com.gxa.jjty.core.common.JsonResult;
import com.gxa.jjty.core.exception.BusinessException;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.UnexpectedTypeException;
import java.util.Map;
import java.util.Set;

/**
 * 本质上,就是一个aop的通知,专门用于加强异常出现的时候的抛出通知
 * @author bill
 * @date 2021/10/21 15:20
 */
@RestController
@ControllerAdvice
@Log4j2
public class ExceptionController {
    /**
     * 当有异常发生,抛出通知介入到目标操作
     * 并把异常对象注入到参数Exception中
     * value 表示什么类型的错误或异常才会被处理
     * 我们选择使用Throwable.class(Error和Exception都要记录)
     */


    // 处理第一种校验异常: 将异常信息拼接,返回给前端显示
    @ExceptionHandler({BindException.class, UnexpectedTypeException.class,MethodArgumentNotValidException.class})
    public Map handleBindException(Errors errors){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("0");
        StringBuilder stringBuilder = new StringBuilder();
        errors.getAllErrors().forEach(error->{
            //格式转换错误,返回给前端输入错误
            if(error.getDefaultMessage().contains("Failed to convert property value of type")){
                 stringBuilder.append("输入格式错误");
            }else {
                stringBuilder.append(error.getDefaultMessage()+",");
            }
        });
        jsonResult.setMsg(stringBuilder.toString().substring(0, stringBuilder.toString().length()-1));
        return jsonResult.getDataMap();
    }

    // 处理第二种校验异常: 将异常信息拼接,返回给前端显示
    @ExceptionHandler({ConstraintViolationException.class})
    public Map handleConstraintViolationException(ConstraintViolationException exception) {
        StringBuilder errorInfo = new StringBuilder();
        String errorMessage ;

        Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            errorInfo.append(item.getMessage()).append(",");
        }
        errorMessage = errorInfo.toString().substring(0, errorInfo.toString().length()-1);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("0");
        jsonResult.setMsg(errorMessage);
        return jsonResult.getDataMap();
    }

    @ExceptionHandler(BusinessException.class)
    public Map BusinessExceptionHandler(BusinessException e){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(e.getExceptionCode().getCode());
        jsonResult.setMsg(e.getExceptionCode().getMsg());
        return jsonResult.getDataMap();
    }

    @ExceptionHandler(Exception.class)
    public Map ExceptionHandler(Exception e){
        // 具体操作和三阶段一致: 自定义异常就返给前端,系统异常记录到日志文件(log4j)
        //分割线方便阅读
        log.info("-----------------begin-----------------------");
        // 先记录异常对象的toString状态: 包括异常类型和异常原因
        log.info(e);
        System.out.println("-----------------begin-----------------------");
        e.printStackTrace();

        // 再遍历栈中的异常轨迹: 采用遍历方式
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            log.info(stackTraceElement);
        }
        //分割线方便阅读
        log.info("-------------------end---------------------");
        JsonResult jsonResult = new JsonResult();
//        标准话术
        jsonResult.setCode("500");
        jsonResult.setMsg("服务器开小差了...");

//        测试使用
//        jsonResult.setMsg(e.getMessage());

        return jsonResult.getDataMap();
    }
}
